package com.prism.cluster;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;

import com.prism.moodme.data.Data;
import com.prism.moodme.datastore.AccessDataStore;
import com.prism.moodme.datastore.GeoGenerator;

public class LoadNewData {
	private URL url;
	public static final String user = "1";

	public LoadNewData(URL url){
		setURL(url);
		try{
			init();
			assignCluster();
		}catch(FileNotFoundException e){
			System.out.println("Upload failed!");
			e.printStackTrace();
		}
		catch(SQLException e){
			System.out.println("Upload failed!");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Data Upload completed successfuly!");
	}

	private void assignCluster() throws SQLException {
		ArrayList<Data> newDat = AccessDataStore.getData(user, 999);
		for(Data curr : newDat){
			int clust = getCluster(curr);
			curr.setCondition(clust);
		}
	}

	private int getCluster(Data curr) throws SQLException {
		double minDist = 1000000;
		int minCond = 1;
		for(int i=0; i<Data.conditions.length; i++){
			int cond = i+1;
			ArrayList<Data> cents = AccessDataStore.getCentroid(user, cond);
			double centDist = curr.euclid(cents);
			if(minDist > centDist){
				minDist = centDist;
				minCond = cond;
			}

		}
		return minCond;
	}

	public int init() throws SQLException, IOException{
		Scanner scan;
		scan = new Scanner(new InputStreamReader(url.openStream()));
			while (scan.hasNextLine()) {
				String line=scan.nextLine();
				StringTokenizer tokens=new StringTokenizer(line, "\n\t");
				if (tokens.countTokens()<14) {System.out.println("error parsing"); continue;}
				String username=tokens.nextToken();
				//make sure unseen condition is set to 999
	            int condition=Integer.parseInt(tokens.nextToken());
	            assert(condition == 999);
	            long time=Long.parseLong(tokens.nextToken());
	            double features[]=new double[9];
	            for (int i=0; i<9; i++) {
	            	features[i]=Double.parseDouble(tokens.nextToken());
	            }

	            // TODO current workaround on GPS
	    		double gpsLat = Double.parseDouble(tokens.nextToken());
	    		double gpsLong = Double.parseDouble(tokens.nextToken());
	    		Data data=new Data(username,condition,features,gpsLong,gpsLat,time);
	    		AccessDataStore.updateData(data);
			}
			scan.close();

		return 0;
	}

	public void setURL(URL url) {
		this.url = url;
	}

	public URL getURL() {
		return url;
	}
}
